package com.yc.game;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;

import com.yc.game.LLKGame.LLKGameListener;

import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.Component;

public class LLKWin {

	private JFrame frame;
	LLKGame game = new LLKGame();
	JButton[][] map;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					LLKWin window = new LLKWin();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public LLKWin() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JPanel panel = new JPanel();
		frame.getContentPane().add(panel, BorderLayout.CENTER);
		
		JPanel panel_1 = new JPanel();
		panel_1.setPreferredSize(new Dimension(100, 10));
		FlowLayout flowLayout = (FlowLayout) panel_1.getLayout();
		frame.getContentPane().add(panel_1, BorderLayout.EAST);
		
		JButton btnNewButton = new JButton("開始遊戲");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				game.build(5, 6);
			}
		});
		panel_1.add(btnNewButton);
		
		JButton btnNewButton_1 = new JButton("退出");
		panel_1.add(btnNewButton_1);
		
		game.setLlkGameListener(new LLKGameListener() {

			@Override
			public void oninit(int x, int y, char c) {
				map[y][x].setText(c+"");
			}

			@Override
			public void onchoose(int x, int y) {
				map[y][x].setText("(" + map[y][x].getText() + ")");
			}

			@Override
			public void oncancel(int x, int y) {
				map[y][x].setText(map[y][x].getText().replaceAll("\\W", ""));
			}

			@Override
			public void ondisappe(int x, int y) {
				map[y][x].setText(null);
				map[y][x].setEnabled(false);
			}

			@Override
			public void onbegin(int width, int height) {
				panel.setLayout(new GridLayout(height, width, 0, 0));
				panel.removeAll();
				map = new JButton[height][width];
				for (int y = 0; y < height; y++) {
					for (int x = 0; x < width; x++) {
						panel.add(map[y][x] = new JButton());
						int _x = x, _y = y;
						map[y][x].addActionListener(e->{
							game.choose(_x, _y);
						});
					}
				}
			}
			
		});
		
		game.build(6, 5);
		
	}

}
